import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Button,
  Space,
  Radio,
  Upload,
  Modal,
  message,
} from 'antd'
import { Link } from 'react-router-dom'
import Channel from 'components/Channel'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import styles from './index.module.scss'
import { CloudUploadOutlined } from '@ant-design/icons'
import { baseURL } from 'utils/request'
import { addArticle, editArticleByID, getArticleByID } from 'api/article'
export default class ArticlePublish extends Component {
  state = {
    type: 1,
    fileList: [],
    previewVisible: false,
    previewImage: '',
    loading: false,
    id: this.props.match.params.id,
  }
  formRes = React.createRef()
  async componentDidMount() {
    const { id } = this.state
    if (!!id) {
      const {
        data: { channel_id, content, cover, title },
      } = await getArticleByID(id)
      this.setState({
        type: cover.type,
        fileList: cover.images.map((item) => ({ url: item })),
      })
      this.formRes.current.setFieldsValue({
        title,
        channel_id,
        content,
        type: cover.type,
      })
    }
  }
  render() {
    const { type, fileList, previewVisible, previewImage, loading, id } =
      this.state
    return (
      <Card
        className={styles.articlePublish}
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{!!id ? '修改文章' : '发布文章'}</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          ref={this.formRes}
          labelCol={{ span: 3 }}
          size="large"
          onFinish={this.onFinish}
          initialValues={{ content: '', title: '', type }}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input placeholder="请输入标题"></Input>
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择频道' }]}
          >
            <Channel></Channel>
          </Form.Item>
          <Form.Item label="封面" name="type">
            <Radio.Group onChange={this.onRadioChange}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          {type !== 0 && (
            <Form.Item wrapperCol={{ offset: 3 }}>
              <Upload
                listType="picture-card"
                action={`${baseURL}upload`}
                fileList={fileList}
                onChange={this.onFileChange}
                name="image"
                method="POST"
                onPreview={this.onPreview}
                beforeUpload={this.beforeUpload}
              >
                {fileList.length < type && <CloudUploadOutlined />}
              </Upload>
            </Form.Item>
          )}
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入内容' }]}
          >
            <ReactQuill theme="snow" placeholder="请输入内容" />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 3 }}>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                size="large"
                loading={loading}
              >
                {!!id ? '编辑文章' : '发布文章'}
              </Button>
              <Button size="large" onClick={this.addDraft} loading={loading}>
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
        <Modal
          visible={previewVisible}
          title="预览图片"
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </Card>
    )
  }
  onFinish = (val) => {
    this.save(val)
  }
  save = async (val, draft = false) => {
    try {
      // 添加loading效果
      this.setState({
        loading: true,
      })

      const { type, fileList, id } = this.state

      if (type !== fileList.length) {
        message.warn('上传图片数量不对')
        throw new Error()
      }
      val.cover = {
        type: val.type,
        images: fileList.map((item) => item.url || item?.response?.data.url),
      }
      delete val.type
      if (!!id) {
        await editArticleByID(val, id, draft)
        message.success('修改成功！')
      } else {
        await addArticle(val, draft)
        message.success('发布成功！')
      }

      this.setState({
        loading: false,
      })
      this.props.history.push('/home/list')
    } catch (err) {
      console.dir(err)
      this.setState({
        loading: false,
      })
    }
  }
  addDraft = async () => {
    try {
      const val = await this.formRes.current.validateFields()
      this.save(val, true)
    } catch (err) {
      console.dir(err)
    }
  }
  onRadioChange = (e) => {
    this.setState({
      type: e.target.value,
      fileList: [],
    })
  }
  onFileChange = ({ file, fileList }) => {
    this.setState({
      fileList,
    })
  }
  onPreview = (file) => {
    this.setState({
      previewVisible: true,
      previewImage: file.url || file.response.data.url,
    })
  }
  handleCancel = () => {
    this.setState({
      previewVisible: false,
      previewImage: '',
    })
  }
  beforeUpload = (file) => {
    if (file.size / 1024 > 500) {
      message.error('图片大小大于500kb')
      return Upload.LIST_IGNORE
    }
    if (!['image/jpeg', 'image/png'].includes(file.type)) {
      message.error('图片格式仅限于/png/jpeg')
      return Upload.LIST_IGNORE
    }
    return true
  }
}
